package org.mikrosopht.client;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import org.cobogw.gwt.user.client.ui.Rating;
import org.cobogw.gwt.user.client.ui.RatingListener;

public class MovieRating extends Composite implements RatingListener, RequestCallback {
  private String movieName;
  private int currentValue;
  private Rating ratingWidget;

  public MovieRating(String movieName, int value) {
    this.movieName = movieName;
    this.currentValue = value;
    ratingWidget = new Rating(value, 5);
    ratingWidget.addRatingListerner(this);
    initWidget(ratingWidget);
  }

  public void onHover(Rating sender, int index) {
  }
  public void onSelect(Rating sender, int index) {
    int rating = sender.getRating();
    // If user clicks on same rating, remove rating value.
    if (rating == currentValue) {
      rating = 0;
    }
    currentValue = rating;
    String url = URL.encode(MovieVoteConstants.SETRATING_URL + "/" + movieName + "/" + rating + "/");
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {
      builder.sendRequest(null, this);
    } catch (RequestException e) {
      Window.alert("Couldn't retrieve JSON: " + e);
    }
  }

  public void onError(Request request, Throwable exception) {
    Window.alert("Couldn't retrieve JSON: " + exception);
  }
  public void onResponseReceived(Request request, Response response) {
    if (response.getStatusCode() == 200) {
      ratingWidget.setRating(currentValue);
    } else {
      Window.alert("Couldn't set rating: " + response.getStatusText());
    }
  }
}
